from django.db import models
from django.utils import timezone
import json


class Category(models.Model):
    """eBay类目模型"""
    id = models.AutoField('编号', primary_key=True) 
    category_id = models.CharField(max_length=255, unique=True, verbose_name="类目编号")
    category_name = models.CharField(max_length=255, verbose_name="类目名称")
    parent_id = models.CharField(max_length=255, null=True, blank=True, verbose_name="父类目ID")
    level = models.IntegerField(default=1, verbose_name="类目层级")
    leaf_category = models.BooleanField(default=False, verbose_name="是否叶子类目")
    category_path = models.TextField(null=True, blank=True, verbose_name="类目路径")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        db_table = 'ebay_category'
        verbose_name = 'eBay类目'
        verbose_name_plural = 'eBay类目'
        ordering = ['level', 'category_id']
        constraints = [
            models.UniqueConstraint(fields=['category_id', 'parent_id'], name='unique_category_parent')
        ]
    def __str__(self):
        return f"{self.category_name} ({self.category_id})"
    
    @property
    def children(self):
        """获取子类目"""
        return Category.objects.filter(parent_id=self.category_id)
    
    @property
    def parent(self):
        """获取父类目"""
        if self.parent_id:
            return Category.objects.filter(category_id=self.parent_id).first()
        return None


class Product(models.Model):
    """eBay商品模型"""
    id = models.AutoField('编号', primary_key=True) 
    item_id = models.CharField(max_length=50, unique=True, verbose_name="商品ID")
    title = models.CharField(max_length=500, verbose_name="商品标题")
    category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="所属类目")
    ebay_category_id = models.CharField(max_length=255, verbose_name="eBay类目ID", db_index=True)
    
    # 价格信息
    current_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name="当前价格")
    currency = models.CharField(max_length=10, default='USD', verbose_name="货币")
    
    # 商品信息
    condition = models.CharField(max_length=50, null=True, blank=True, verbose_name="商品状态")
    listing_type = models.CharField(max_length=50, null=True, blank=True, verbose_name="销售类型")
    buy_it_now_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name="一口价")
    
    # 卖家信息
    seller_username = models.CharField(max_length=100, null=True, blank=True, verbose_name="卖家用户名")
    seller_feedback_score = models.IntegerField(null=True, blank=True, verbose_name="卖家评分")
    
    # 商品详情
    gallery_url = models.URLField(null=True, blank=True, verbose_name="图片URL")
    view_item_url = models.URLField(null=True, blank=True, verbose_name="商品链接")
    shipping_cost = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name="运费")
    location = models.CharField(max_length=200, null=True, blank=True, verbose_name="商品位置")
    
    # 时间信息
    start_time = models.DateTimeField(null=True, blank=True, verbose_name="开始时间")
    end_time = models.DateTimeField(null=True, blank=True, verbose_name="结束时间")
    
    # 其他信息
    watch_count = models.IntegerField(null=True, blank=True, verbose_name="关注数")
    bid_count = models.IntegerField(null=True, blank=True, verbose_name="出价次数")
    
    # 扩展字段 - 存储原始API返回的JSON数据
    raw_data = models.JSONField(null=True, blank=True, verbose_name="原始数据")
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        db_table = 'ebay_product'
        verbose_name = 'eBay商品'
        verbose_name_plural = 'eBay商品'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['ebay_category_id']),
            models.Index(fields=['current_price']),
            models.Index(fields=['created_at']),
        ]
    
    def __str__(self):
        return f"{self.title[:50]}..."


class ApiLog(models.Model):
    """API调用日志"""
    api_type = models.CharField(max_length=50, verbose_name="API类型")  # taxonomy, finding
    operation = models.CharField(max_length=100, verbose_name="操作类型")
    request_data = models.JSONField(null=True, blank=True, verbose_name="请求数据")
    response_data = models.JSONField(null=True, blank=True, verbose_name="响应数据")
    status = models.CharField(max_length=20, verbose_name="状态")  # success, error
    error_message = models.TextField(null=True, blank=True, verbose_name="错误信息")
    execution_time = models.FloatField(null=True, blank=True, verbose_name="执行时间(秒)")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        db_table = 'ebay_api_log'
        verbose_name = 'API调用日志'
        verbose_name_plural = 'API调用日志'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.api_type} - {self.operation} ({self.status})"


class SyncTask(models.Model):
    """同步任务模型"""
    TASK_TYPE_CHOICES = [
        ('category', '类目同步'),
        ('product', '商品同步'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '待执行'),
        ('running', '执行中'),
        ('completed', '已完成'),
        ('failed', '失败'),
    ]
    
    task_type = models.CharField(max_length=20, choices=TASK_TYPE_CHOICES, verbose_name="任务类型")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name="任务状态")
    category_id = models.CharField(max_length=255, null=True, blank=True, verbose_name="类目ID")
    total_items = models.IntegerField(default=0, verbose_name="总数量")
    processed_items = models.IntegerField(default=0, verbose_name="已处理数量")
    error_message = models.TextField(null=True, blank=True, verbose_name="错误信息")
    started_at = models.DateTimeField(null=True, blank=True, verbose_name="开始时间")
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name="完成时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        db_table = 'ebay_sync_task'
        verbose_name = '同步任务'
        verbose_name_plural = '同步任务'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.get_task_type_display()} - {self.get_status_display()}"
